package mylab.utils.location.ip;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import mylab.utils.common.StrUtil;
import org.lionsoul.ip2region.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * Ip 地址转换
 * </p>
 *
 * @date Created in 2019/11/6 10:42
 */
@Slf4j
public class Ip2Region {

    /**
     * 本机回环地址
     */
    private static final String LOCAL_INNER_LOOP_IP = "0:0:0:0:0:0:0:1";

    /**
     * 本机IP地址
     */
    private static final String LOCAL_IP = "127.0.0.1";

    private static final String IP_DB_FILE = "ip/ip2region.db";

    /**
     * 根据ip获取城市信息
     */
    public static String getAddress(String ip) {
        if (StrUtil.equals(ip, LOCAL_INNER_LOOP_IP)) {
            ip = LOCAL_IP;
        }
        String address = "";
        boolean ipAddress = Util.isIpAddress(ip);
        if (!ipAddress) {
            return address;
        }
        try {
            DbConfig config = new DbConfig();
            InputStream streamSafe = ResourceUtil.getStreamSafe(IP_DB_FILE);

            if (streamSafe == null) {
                log.error("【获取地理位置】未找到 IP 数据库文件，请前往 https://github.com/xkcoding/magic-starter/tree/master/magic-core-tool/src/main/resources/ip/ip2region.db 下载！");
                return address;
            }

            DbSearcher searcher = new DbSearcher(config, IoUtil.readBytes(streamSafe));
            DataBlock dataBlock = searcher.memorySearch(ip);

            // dataBlock格式：城市Id|国家|区域|省份|城市|ISP
            // region格式：国家|区域|省份|城市|ISP
            // region例如：中国|0|浙江省|杭州市|电信
            String region = dataBlock.getRegion();

            // 按 | 切分
            List<String> regionList = Splitter.on("|").splitToList(region);
            // 过滤为 0 的数据
            List<String> regionListFilter = regionList.stream().filter(s -> !StrUtil.equals(StrUtil.ZERO, s)).distinct().collect(Collectors.toList());
            // 再用 | 拼接回来
            address = Joiner.on("|").join(regionListFilter);
        } catch (IOException | DbMakerConfigException e) {
            log.error("【获取地理位置】发生异常: ", e);
        }
        return address;
    }
}
